import multiprocessing
import sys
from time import sleep
from datetime import datetime, time
from logging import INFO

from vnsumscope.trader.setting import SETTINGS

SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True

username = sys.argv[1] if len(sys.argv) > 1 else '10002'

hft_setting = {
    "用户名": str(username),
    "密码": "",
    "服务器": "47.100.198.101:32201",
}

"""
1. 策略收到仿真环境的tick数据，合成bar并触发策略on_bar
2. on_bar回调中收到bar数据即下单，便捷展示策略在仿真环境自动下单
"""

from vnsumscope.app.cta_strategy import (
    CtaTemplate,
    StopOrder,
    TickData,
    BarData,
    TradeData,
    OrderData,
    BarGenerator,
    ArrayManager,
)


class BondDemoForSimStrategy(CtaTemplate):
    author = "用Python的交易员"

    fast_window = 10
    slow_window = 20

    fast_ma0 = 0.0
    fast_ma1 = 0.0

    slow_ma0 = 0.0
    slow_ma1 = 0.0

    parameters = ["fast_window", "slow_window"]
    variables = ["fast_ma0", "fast_ma1", "slow_ma0", "slow_ma1"]

    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()

        self.last_tick = None

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        
        self.write_log("策略初始化")
        # self.load_tick(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")
        self.put_event()

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

        self.put_event()

    def on_tick(self, tick: TickData):
        """
        Callback of new tick data update.
        """ 
        self.write_log(str(tick))
        # self.last_tick = tick
        self.bg.update_tick(tick)
        self.put_event()

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        print(str(bar))

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        # self.write_log(str(order))

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.write_log(str(trade))
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass



def run_sim():
    """
    Running in the child process.
    """

    from vnsumscope.event import EventEngine
    
    from vnsumscope.trader.engine import MainEngine

    from vnsumscope.gateway import SumscopeGateway
    from vnsumscope.app.cta_strategy import CtaStrategyApp
    from vnsumscope.app.cta_strategy.base import EVENT_CTA_LOG

    SETTINGS["log.file"] = True

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    main_engine.add_gateway(SumscopeGateway)
    cta_engine = main_engine.add_app(CtaStrategyApp)
    main_engine.write_log("主引擎创建成功")

    cta_engine.init_engine()

    log_engine = main_engine.get_engine("log")
    event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
    main_engine.write_log("注册日志事件监听")

    main_engine.connect(hft_setting, "SUMSCOPE")
    main_engine.write_log("连接SUMSCOPE接口")

    sleep(10)

    #TODO 这里可以通过传入文件地址的方式将策略挂进引擎
    cta_engine.add_strategy(
        BondDemoForSimStrategy, 
        'bond_demo_for_sim_strategy',
        '200210.CFETS',
        setting={}
        )
    cta_engine.init_strategy('bond_demo_for_sim_strategy')
    sleep(5)

    cta_engine.start_strategy('bond_demo_for_sim_strategy')


if __name__ == "__main__":
    run_sim()
